package core

import (
	"context"
	"esc.show/multiple_database/internal/core/databases"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"log"
)

type Core struct {
	ctx        context.Context
	Engine     *gin.Engine
	GinContext *gin.Context
	Db         *gorm.DB
	TenantDb   *gorm.DB
	cancels    []context.CancelFunc
	TenantID   string
	StartHooks []Hooks
}

type Hooks func(core *Core)

func New() *Core {
	return &Core{
		ctx:    context.Background(),
		Engine: gin.Default(),
	}
}

// Run 执行启动
func (c *Core) Run() {
	c.Init()
	c.start()
}

// Init 初始化数据库链接和路由
func (c *Core) Init() {
	c.RegisterDb().UseHooks()
}

// 启动服务
func (c *Core) start() {
	err := c.Engine.Run(":3000")
	if err != nil {
		log.Fatal(err)
	}
}

// AddHook 添加钩子
func (c *Core) AddHook(dispatches ...Hooks) *Core {
	c.StartHooks = dispatches
	return c
}

// UseHooks 加载启动项
func (c *Core) UseHooks() *Core {
	if len(c.StartHooks) != 0 {
		for _, hook := range c.StartHooks {
			hook(c)
		}
	}
	return c
}

// RegisterDb  注册数据库
func (c *Core) RegisterDb() *Core {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("database.username"),
		viper.GetString("database.password"),
		viper.GetString("database.host"),
		viper.GetString("database.port"),
		viper.GetString("database.db"),
	)
	c.Db = databases.RegisterDb(c.Db, dsn)
	return c
}
